<template>
  <div>
    <Tabs
      type="card"
      v-model="activeKey"
      @on-click="sel"
      @on-tab-remove="remove"
      style="padding-top: 10px; margin-bottom: -16px"
      closable
    >
      <TabPane
        :label="pane.title"
        :name="pane.key"
        v-for="pane in panes"
        :key="pane.name"
        :closable="pane.closable"
      >
      </TabPane>
    </Tabs>
  </div>
</template>
<script setup>
import { useTabStore } from '../../stores/tabs'
import _ from 'lodash'
const emit = defineEmits(['toActive'])
const router = useRouter()
const store = useTabStore()

let activeKey = ref(store.tabs[0].key)
let panes = ref(store.tabs)

const sel = (key) => {
  let name = _.find(panes.value, { key: key }).name

  emit('toActive', name)
  if (location.pathname != key) {
    router.push(key)
  }
}

const remove = (targetKey) => {
  store.RemoveTab(targetKey)
}

watch(
  () => store.tabs,
  (tab) => {
    activeKey.value = tab[tab.length - 1].key
    panes.value = store.tabs
    router.push(tab[tab.length - 1].key)
  }
)

watch(
  () => store.tabKey,
  (key) => {
    activeKey.value = key
  }
)
</script>